package com.shop.utils;

import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedList;
import java.util.List;

/**
 * minio工具类
 */
@Component
public class MinioUtils {
    private static final String endpoint = "http://106.13.226.130:9000";
    private static final String ACCESS_KEY = "username";
    private static final String SECRET_KEY = "password";
    private static final String BUCKET = "goods";


    public static void uploadFile(String fileName,String originalFilename) throws NoSuchAlgorithmException, InvalidKeyException, IOException {
        try {
            MinioClient minioClient=MinioClient.builder().endpoint(endpoint).credentials(ACCESS_KEY, SECRET_KEY).build();
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(BUCKET).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(BUCKET).build());
            } else {
                System.out.println("Bucket 'goods' already exists.");
            }
            minioClient.uploadObject(UploadObjectArgs.builder().bucket(BUCKET).object(fileName).filename("C:\\Users\\dell\\Desktop\\graduation-project\\shop_backend\\src\\main\\resources\\static\\images\\" + originalFilename).build());
        } catch (MinioException e) {
            System.out.println(e);
        }
    }

    public static void deleteFile(String fileName) throws NoSuchAlgorithmException, InvalidKeyException, IOException {
        try {
            MinioClient minioClient=MinioClient.builder().endpoint(endpoint).credentials(ACCESS_KEY, SECRET_KEY).build();
            List<DeleteObject> objects = new LinkedList<>();
            objects.add(new DeleteObject(fileName));
            Iterable<Result<DeleteError>> results=minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(BUCKET).objects(objects).build());
            for (Result<DeleteError> result : results) {
                DeleteError error = result.get();
                System.out.println("Error in deleting object " + error.objectName() + "; " + error.message());
            }
        } catch (MinioException e) {
            System.out.println(e);
        }
    }
}
